package com.controller;

import com.alibaba.fastjson.JSON;
import com.domain.InterfaceView;
import com.service.InterfaceViewService;
import com.utils.HttpUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.TestNG;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.util.*;

/**
 * InterfaceViewController
 *
 **/
@Controller
@RequestMapping("/interfaceViewController")
public class InterfaceViewController {

    @Autowired
    private InterfaceViewService interfaceViewService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 保存数据索引
     */
    private List<String> esList = new ArrayList<>();
    /**
     * 存放所有执行失败的用例
     */
    protected Map<String,String> mapStr = new HashMap<>();

    /**
     * 查询所有用例
     * @return
     */
    @RequestMapping(value = "/findAll",method=RequestMethod.POST)
    @ResponseBody
    public List<InterfaceView>  findAll(){
        List<InterfaceView> interfaceViewList = new ArrayList<>();
        interfaceViewList = interfaceViewService.findAll();
        return interfaceViewList;
    }
    /**
     * 查询所有失败用例
     * @return
     */
    @RequestMapping(value = "/findAllFail",method=RequestMethod.POST)
    @ResponseBody
    public List<InterfaceView>  findAllFail(InterfaceView interfaceView){
        interfaceView.setPassOrNot("失败");
        List<InterfaceView> interfaceViewList = new ArrayList<>();
        interfaceViewList = interfaceViewService.findAllfindAllFail(interfaceView);
        return interfaceViewList;
    }
    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/deleteById",method=RequestMethod.POST)
    @ResponseBody
    public String  deleteById(@RequestParam List<Integer> idList){
        try {
            interfaceViewService.deleteById(idList);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

    }
    /**
     * 新增用例
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(InterfaceView interfaceView){
        try {
            interfaceViewService.add(interfaceView);
            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }
    /**
     * 执行所有用例
     * @param idList
     */
    @RequestMapping(value = "/execute", method = RequestMethod.POST)
    @ResponseBody
    public String execute(@RequestParam List<Integer> idList){
        try {

            redisTemplate.opsForValue().set("idSelects", JSON.toJSONString(idList));
            List<InterfaceView> lists = interfaceViewService.findAllTest(idList);
            for(int i=0;i<idList.size();i++){
                redisTemplate.opsForValue().set("interfaceV"+idList.get(i), JSON.toJSONString(lists.get(i)));
            }
            TestNG testNG = new TestNG();
            List<String> list = new ArrayList<>();
            list.add("testng.xml");
            testNG.setTestSuites(list);
            testNG.run();
            List<String> setstr = JSON.parseArray((String) redisTemplate.opsForValue().get("mess"), String.class);
            List<String> failstr = new ArrayList<>(); //存放失败用例
            System.out.println(failstr);
            if(null!=setstr && setstr.size()>0){
                for(String str : setstr){
                    if(str.split("&")[1].equals("失败")){ //接口名+返回值
                        failstr.add(str.split("&")[3]);
                    }
                    InterfaceView interfaceView1 = new InterfaceView();
                    interfaceView1.setResponseId(str.split("&")[0]);
                    interfaceView1.setPassOrNot(str.split("&")[1]);
                    interfaceView1.setId(Integer.valueOf(str.split("&")[2]));
                    interfaceViewService.update(interfaceView1);
                }
//                if(null!=failstr && failstr.size()>0){
//                    pushDing(failstr);
//                }
            }
            return "success";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 定时执行所有用例
     *
     */
    @RequestMapping(value = "/executeTimer", method = RequestMethod.POST)
    @ResponseBody
    public String executeTimer(@RequestParam List idList){
        try {
            List<Integer> idLists = new ArrayList<>();
            for(int i=0;i<idList.size()-1;i++){
                idLists.add(Integer.parseInt((String) idList.get(i)));
            }
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    timerCommon(idLists);
                }
            }, 0,Integer.parseInt((String)idList.get(idList.size()-1)));// 设定指定的时间time,此处为2000毫秒
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

    }

    public void timerCommon(List<Integer> idList) {
        try {
            redisTemplate.opsForValue().set("idSelects", JSON.toJSONString(idList));
            List<InterfaceView> lists = interfaceViewService.findAllTest(idList);
            for(int i=0;i<idList.size();i++){
                redisTemplate.opsForValue().set("interfaceV"+idList.get(i), JSON.toJSONString(lists.get(i)));
            }
            TestNG testNG = new TestNG();
            List<String> list = new ArrayList<>();
            list.add("testng.xml");
            testNG.setTestSuites(list);
            testNG.run();
            List<String> setstr = JSON.parseArray((String) redisTemplate.opsForValue().get("mess"), String.class);
            List<String> failstr = new ArrayList<>(); //存放失败用例
            if(null!=setstr && setstr.size()>0){
                for(String str : setstr){
                    if(str.split("&")[1].equals("失败")){ //接口名+返回值
                        failstr.add(str.split("&")[3]);
                    }
                    InterfaceView interfaceView1 = new InterfaceView();
                    interfaceView1.setResponseId(str.split("&")[0]);
                    interfaceView1.setPassOrNot(str.split("&")[1]);
                    interfaceView1.setId(Integer.valueOf(str.split("&")[2]));
                    interfaceViewService.update(interfaceView1);
                }
                if(null!=failstr && failstr.size()>0){
                    pushDing(failstr);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/index")
    public String testJsp(){
        return "index";
    }

    @RequestMapping("/result")
    public String resultJsp(){
        return "result";
    }

    private void pushDing(List<String> failstr){
        //钉钉机器人地址（配置机器人的webhook）
        String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=a3827921af7edb85273b0643ff9a322ca5dd67d3a0e135eacdd5bbe2152a1e10";
        //是否通知所有人
        boolean isAtAll = true;
        //通知具体人的手机号码列表
        List<String> mobileList = new ArrayList();
        mobileList.add("17711111111");
        //钉钉机器人消息内容
        StringBuffer sb = new StringBuffer("报错的接口名称如下：\n");
        if(failstr.size()>0){
            for(int i=0;i<failstr.size();i++){
                sb.append(failstr.get(i)+"；\n");
            }
        }
        String content = "【测试环境】监控报警：\n"+sb.toString()+"详情请使用PC打开网页： http://localhost:8081/interfaceViewController/result \n";
        //组装请求内容
        String reqStr = buildReqStr(content, isAtAll, mobileList);
        //推送消息（http请求）
        String result = HttpUtils.postJson(dingUrl, reqStr, null);
        System.out.println("result == " + result);
    }
    /**
     * 组装请求报文
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = new HashMap();
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = new HashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        Map<String, Object> reqMap = new HashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        return JSON.toJSONString(reqMap);
    }

}
